package models;

import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;

import play.data.validation.Email;
import play.data.validation.Required;
import play.db.jpa.Model;
import play.libs.Mail;
import controllers.Application;

@Entity
public class Student extends Model {
	/**
	 * 
	 */
	private static final long serialVersionUID = 2872722648035684566L;

	@Column (length = 50, unique = true)
	@Required
	public String username; // unique GUC username

	@Column (length = 32)
	@Required
	public String pwd; // hashed :)

	@Email
	@Column (length = 100, unique = true)
	@Required
	public String email;

	@Column (length = 16)
	@Required
	public String studentID; // GUC ID, in the form: 13-7839

	// public boolean isInstructor; // could students be instructors?

	@ManyToMany (mappedBy = "students")
	public List<Tutorial> tutorials;

	@OneToMany (mappedBy = "student")
	public List<Submission> submissions;

	@OneToMany (mappedBy = "student")
	public List<CourseRequest> requests;

	@OneToOne (mappedBy = "studentAccount")
	public Instructor instructorAccount;

	/**
	 * Full constructor
	 * 
	 * @param username
	 *            GUC username
	 * @param ID
	 *            full GUC ID
	 */
	public Student (String username, String ID) {
		this.username = username;
		this.email = username + "@student.guc.edu.eg";
		this.studentID = ID;
		String pwd = Application.randomHash(4);
		this.pwd = Application.hash(pwd);
		this.welcome(pwd);
	}

	/**
	 * just a nice welcome message. With a password ;)
	 * 
	 * @param pwd
	 *            password to include in the email
	 */
	public void welcome(String pwd) {
		Mail.send("gapc@guc.edu.eg", username + "@student.guc.edu.eg", "Welcome to G-APC", "Hello, " + username + ". You can login using the password: " + pwd);
	}

	public String toString() {
		return username;
	}

	public static boolean connect(String username2, String password) {
		Student student = Student.find("select s from Student s where (s.username=?	or s.studentID=?) and s.pwd=? ", username2, username2, Application.hash(password)).first();
		return student != null;
	}

	public static class Object {
		public long id;

		public String username;

		public Object (long id, String username) {
			this.id = id;
			this.username = username;
		}
	}
}
